#include<iostream>
#include<string>
using namespace std;
static int num = 0;
class TreeNode {
public:
	char Data;
	TreeNode* left;
	TreeNode* right;
	int n;
	int m;
	TreeNode(char ch = '0') {
		m = 0;
		n = 0;
		Data = ch;
		left = right = NULL;
	}
};
class Tree {
public:
	TreeNode* tmp;
	Tree() {
	}
	void Init(TreeNode*& p) {
		char ch;
		cin >> ch;
		if (ch == '0') {
			p = NULL;
		}
		else {
			p = new TreeNode(ch);
			Init(p->left);
			Init(p->right);
		}
	}
	void made(TreeNode* p) {
		if (p == NULL) {
			return;
		}
		if (p->left != NULL) {
			p->left->n = p->n + 1;
		}
		if (p->right != NULL) {
			p->right->n = p->n + 1;
		}
		made(p->left);
		made(p->right);
	}
	void sum(TreeNode* p) {
		if (p == NULL) {
			return;
		}
		if (p->left == NULL && p->right == NULL) {
			num += p->m * p->n;
		}
		sum(p->left);
		sum(p->right);
	}
	void ad(TreeNode* p, int* a, int& n) {
		if (p == NULL) {
			return;
		}
		if (p->left == NULL && p->right == NULL && p->m == 0) {
			p->m = a[n++];
		}
		ad(p->left, a, n);
		ad(p->right, a, n);
	}
	void print(TreeNode* p) {
		if (p == NULL) {
			return;
		}
		if (p->left == NULL && p->right == NULL) {
			cout << p->Data << endl;
		}
		print(p->left);
		print(p->right);
	}
};
int main()
{
	int t;
	cin >> t;
	for (int i = 0; i < t; i++) {
		num = 0;
		Tree T;
		T.Init(T.tmp);
		T.made(T.tmp);
		int k;
		cin >> k;
		int* a = new int[k];
		for (int j = 0; j < k; j++) {
			cin >> a[j];
		}
		int l = 0;
		T.ad(T.tmp, a, l);
		T.sum(T.tmp);
		//T.print(T.tmp);
		cout << num << endl;
	}
	return 0;
}